package com.liaozibo.demo.seckill.support.config;

import com.liaozibo.demo.seckill.support.properties.RedisPoolProperties;
import com.liaozibo.demo.seckill.support.properties.RedisProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class JedisConfig {
    @Autowired
    private RedisPoolProperties redisPoolProperties;

    @Autowired
    private RedisProperties redisProperties;

    /**
     * 对象资源池初始化配置
     * */
    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(redisPoolProperties.getMaxTotal());
        jedisPoolConfig.setMaxIdle(redisPoolProperties.getMaxIdle());
        jedisPoolConfig.setMinIdle(redisPoolProperties.getMinIdle());
        jedisPoolConfig.setMaxWaitMillis(redisPoolProperties.getMaxWaitMillis());
        jedisPoolConfig.setTestOnBorrow(redisPoolProperties.isTestOnBorrow());
        jedisPoolConfig.setTestOnReturn(redisPoolProperties.isTestOnReturn());
        jedisPoolConfig.setTestWhileIdle(redisPoolProperties.isTestWhileIdle());
        jedisPoolConfig.setNumTestsPerEvictionRun(redisPoolProperties.getNumTestsPerEvictionRun());
        jedisPoolConfig.setTimeBetweenEvictionRunsMillis(redisPoolProperties.getTimeBetweenEvictionRunsMillis());
        return jedisPoolConfig;
    }

    /**
     * redis 单机资源池
     * */
    @Bean
    public JedisPool jedisPool(JedisPoolConfig jedisPoolConfig) {
        String host = redisProperties.getHost();
        int port = redisProperties.getPort();
        int timeout = redisProperties.getTimeout(); // 单位秒 当客户端闲置多长时间后关闭连接，如果指定为0，表示关闭该功能  查看方式：客户端> config get timeout
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout);
        return jedisPool;
    }

}
